package com.cn.kehong.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cn.kehong.api.*;
import com.cn.kehong.conf.Config;
import com.cn.kehong.dao.*;
import com.cn.kehong.domain.*;
import com.cn.kehong.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@EnableScheduling
@Service
public class ProductPeiJizhongServiceImpl implements IProductPeiJizhongService {

    @Autowired
    private ProductPeiJizhongMapper productPeiJizhongMapper;

    @Autowired
    private ProductPeiTouMapper productPeiTouMapper;

    @Autowired
    private Config config;

    @Autowired
    private ProductPeiJobSupplierMapper productPeiJobSupplierMapper;

    @Autowired
    private ISysItemService sysItemService;

    @Autowired
    private IProductPeiJizhongCollectService productPeiJizhongCollectService;

    @Override
    public List<ProductPeiJizhongVo> getJizhongList(QueryForm queryForm) throws Exception {
//        ProductPeiTouExample peiTouExample = new ProductPeiTouExample();
//        peiTouExample.createCriteria().andJiWeightStatusEqualTo("2").andStatusEqualTo((Constants.NORMAL_STATUS));
        //获取计重已完成数据
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectPcByTou(queryForm);
        List<ProductPeiJizhongVo> newProductPeiJizhongVos = new ArrayList<>();
        for (ProductPeiTou peiTou :productPeiTous){
            ProductPeiJizhongExample jizhongExample = new ProductPeiJizhongExample();
            jizhongExample.createCriteria().andPeiIdEqualTo(peiTou.getId()).andStatusEqualTo((Constants.NORMAL_STATUS));
            List<ProductPeiJizhong> productPeiJizhongs = productPeiJizhongMapper.selectByExample(jizhongExample);
            ProductPeiJizhongVo aggregatedVo = new ProductPeiJizhongVo();
            for (ProductPeiJizhong vo : productPeiJizhongs) {
                    aggregatedVo.setFactoryName(peiTou.getFactoryName());
                    aggregatedVo.setQiStartTime(peiTou.getQiStartTime());
                    aggregatedVo.setJiWeightTime(peiTou.getJiWeightTime());
                    aggregatedVo.setBanCi(peiTou.getBanCiCn());
                    aggregatedVo.setJiWeightStatus(peiTou.getJiWeightStatusCn());
                    aggregatedVo.setJiWeightUser(peiTou.getJiWeightUser());
                    aggregatedVo.setGradeValueName(peiTou.getProductName() + peiTou.getGradeValue());
                    aggregatedVo.setBoxCode(peiTou.getBoxCode());
                    aggregatedVo.setStartCode(peiTou.getStartCode());

                if ("原料".equals(vo.getMaterialType())||"主料".equals(vo.getMaterialType())) {
                        if ("去离子水".equals(vo.getMaterialGrade())) {
                            aggregatedVo.setWaterSupplier(vo.getSupplierNum());
                            aggregatedVo.setWaterActual(vo.getActualNum());
                            aggregatedVo.setWaterRefill(vo.getExtendNum());
                            aggregatedVo.setWaterTotal(vo.getTotalNum());
                        } else if ("磷酸铁".equals(vo.getMaterialGrade())) {
                            aggregatedVo.setFeSupplier(vo.getSupplierNum());
                            aggregatedVo.setFeActual(vo.getActualNum());
                            aggregatedVo.setFeRefill(vo.getExtendNum());
                            aggregatedVo.setFeTotal(vo.getTotalNum());
                        } else if ("碳酸锂".equals(vo.getMaterialGrade())) {
                            aggregatedVo.setLiSupplier(vo.getSupplierNum());
                            aggregatedVo.setLiActual(vo.getActualNum());
                            aggregatedVo.setLiRefill(vo.getExtendNum());
                            aggregatedVo.setLiTotal(vo.getTotalNum());
                        }
                    } else if ("辅料".equals(vo.getMaterialType())) {
                        if ("钛".equals(vo.getMaterialGrade())) {
                            aggregatedVo.settSupplier(vo.getSupplierNum());
                            aggregatedVo.settActual(vo.getActualNum());
                            aggregatedVo.settRefill(vo.getExtendNum());
                            aggregatedVo.settTotal(vo.getTotalNum());
                        } else if ("聚乙二醇".equals(vo.getMaterialGrade())) {
                            aggregatedVo.setPegSupplier(vo.getSupplierNum());
                            aggregatedVo.setPegActual(vo.getActualNum());
                            aggregatedVo.setPegRefill(vo.getExtendNum());
                            aggregatedVo.setPegTotal(vo.getTotalNum());
                        }else if ("氟化锂".equals(vo.getMaterialGrade())) {
                            aggregatedVo.setFhlSupplier(vo.getSupplierNum());
                            aggregatedVo.setFhlActual(vo.getActualNum());
                            aggregatedVo.setFhlRefill(vo.getExtendNum());
                            aggregatedVo.setFhlTotal(vo.getTotalNum());
                        } else if ("葡萄糖".equals(vo.getMaterialGrade())) {
                            aggregatedVo.setGsSupplier(vo.getSupplierNum());
                            aggregatedVo.setGsActual(vo.getActualNum());
                            aggregatedVo.setGsRefill(vo.getExtendNum());
                            aggregatedVo.setGsTotal(vo.getTotalNum());
                        }
                    }
            }
            newProductPeiJizhongVos.add(aggregatedVo);
        }

        if (!newProductPeiJizhongVos.isEmpty()) {
            newProductPeiJizhongVos.get(0).setCount(newProductPeiJizhongVos.size());
        }

        return newProductPeiJizhongVos;
    }

    @Override
    public List<ProductPeiJizhongVo> getJizhongListByDay(QueryForm queryForm) throws Exception {
        // 如果没有传时间
        if (StringUtils.isEmpty(queryForm.getStartTime())) {
            // 判断当前时间属于白班还是夜班
            // 获取当前时间
//            LocalDateTime now = LocalDateTime.now();
//            setShiftTimes(queryForm, now);
            Map<String,String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
            queryForm.setBanCi(dutyMap.get("whiteDay"));
            queryForm.setDutyDay(dutyMap.get("dutyDay"));
        }
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectPcByTou(queryForm);
        Map<String, ProductPeiJizhongVo> factoryAggregatedMap = new HashMap<>();

        for (ProductPeiTou peiTou : productPeiTous) {
            ProductPeiJizhongExample jizhongExample = new ProductPeiJizhongExample();
            jizhongExample.createCriteria().andPeiIdEqualTo(peiTou.getId()).andStatusEqualTo(Constants.NORMAL_STATUS);
            List<ProductPeiJizhong> productPeiJizhongs = productPeiJizhongMapper.selectByExample(jizhongExample);

            for (ProductPeiJizhong vo : productPeiJizhongs) {
                String factoryName = peiTou.getFactoryName();
                ProductPeiJizhongVo aggregatedVo = factoryAggregatedMap.computeIfAbsent(factoryName, k -> new ProductPeiJizhongVo());
                Set<String> peiIds = aggregatedVo.getPeiIds();
                if (peiIds == null) {
                    peiIds = new HashSet<>();
                    aggregatedVo.setPeiIds(peiIds);
                }
                peiIds.add(peiTou.getId());
                aggregatedVo.setCount(productPeiTous.size());
                aggregatedVo.setFactoryName(factoryName);
                aggregatedVo.setQiStartTime(peiTou.getQiStartTime());
                aggregatedVo.setGradeValueName(peiTou.getProductName() + peiTou.getGradeValue());

                // 累加每种材料的总量
                if ("原料".equals(vo.getMaterialType())||"主料".equals(vo.getMaterialType())) {
                    if ("去离子水".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setWaterTotal(String.format("%.3f", getTotal(aggregatedVo.getWaterTotal(), vo.getTotalNum())));
                    } else if ("磷酸铁".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setFeTotal(String.format("%.3f", getTotal(aggregatedVo.getFeTotal(), vo.getTotalNum())));
                    } else if ("碳酸锂".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setLiTotal(String.format("%.3f", getTotal(aggregatedVo.getLiTotal(), vo.getTotalNum())));
                    }
                } else if ("辅料".equals(vo.getMaterialType())) {
                    if ("钛".equals(vo.getMaterialGrade())) {
                        aggregatedVo.settTotal(String.format("%.3f", getTotal(aggregatedVo.gettTotal(), vo.getTotalNum())));
                    } else if ("聚乙二醇".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setPegTotal(String.format("%.3f", getTotal(aggregatedVo.getPegTotal(), vo.getTotalNum())));
                    } else if ("氟化锂".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setFhlTotal(String.format("%.3f", getTotal(aggregatedVo.getFhlTotal(), vo.getTotalNum())));
                    } else if ("葡萄糖".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setGsTotal(String.format("%.3f", getTotal(aggregatedVo.getGsTotal(), vo.getTotalNum())));
                    }
                }

            }
        }
        for (ProductPeiJizhongVo aggregatedVo : factoryAggregatedMap.values()) {
            aggregatedVo.setCount(aggregatedVo.getPeiIds().size());
        }
        return new ArrayList<>(factoryAggregatedMap.values());
    }

    @Override
    public void exportJizhongList(QueryForm queryForm, HttpServletResponse response) throws Exception {
        Map<String, Object> results = Maps.newHashMap();
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectPcByTou(queryForm);
        List<ProductPeiJizhongVo> newProductPeiJizhongVos = new ArrayList<>();
        for (ProductPeiTou peiTou :productPeiTous){
            ProductPeiJizhongExample jizhongExample = new ProductPeiJizhongExample();
            jizhongExample.createCriteria().andPeiIdEqualTo(peiTou.getId()).andStatusEqualTo((Constants.NORMAL_STATUS));
            List<ProductPeiJizhong> productPeiJizhongs = productPeiJizhongMapper.selectByExample(jizhongExample);
            ProductPeiJizhongVo aggregatedVo = new ProductPeiJizhongVo();
            for (ProductPeiJizhong vo : productPeiJizhongs) {
                aggregatedVo.setFactoryName(peiTou.getFactoryName());
                aggregatedVo.setQiStartTime(peiTou.getQiStartTime());
                aggregatedVo.setJiWeightTime(peiTou.getJiWeightTime());
                aggregatedVo.setBanCi(peiTou.getBanCiCn());
                aggregatedVo.setJiWeightStatus(peiTou.getJiWeightStatusCn());
                aggregatedVo.setJiWeightUser(peiTou.getJiWeightUser());
                aggregatedVo.setGradeValueName(peiTou.getProductName() + peiTou.getGradeValue());
                aggregatedVo.setBoxCode(peiTou.getBoxCode());
                aggregatedVo.setStartCode(peiTou.getStartCode());

                if ("原料".equals(vo.getMaterialType())||"主料".equals(vo.getMaterialType())) {
                    if ("去离子水".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setWaterSupplier(vo.getSupplierNum());
                        aggregatedVo.setWaterActual(vo.getActualNum());
                        aggregatedVo.setWaterRefill(vo.getExtendNum());
                        aggregatedVo.setWaterTotal(vo.getTotalNum());
                    } else if ("磷酸铁".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setFeSupplier(vo.getSupplierNum());
                        aggregatedVo.setFeActual(vo.getActualNum());
                        aggregatedVo.setFeRefill(vo.getExtendNum());
                        aggregatedVo.setFeTotal(vo.getTotalNum());
                    } else if ("碳酸锂".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setLiSupplier(vo.getSupplierNum());
                        aggregatedVo.setLiActual(vo.getActualNum());
                        aggregatedVo.setLiRefill(vo.getExtendNum());
                        aggregatedVo.setLiTotal(vo.getTotalNum());
                    }
                } else if ("辅料".equals(vo.getMaterialType())) {
                    if ("钛".equals(vo.getMaterialGrade())) {
                        aggregatedVo.settSupplier(vo.getSupplierNum());
                        aggregatedVo.settActual(vo.getActualNum());
                        aggregatedVo.settRefill(vo.getExtendNum());
                        aggregatedVo.settTotal(vo.getTotalNum());
                    } else if ("聚乙二醇".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setPegSupplier(vo.getSupplierNum());
                        aggregatedVo.setPegActual(vo.getActualNum());
                        aggregatedVo.setPegRefill(vo.getExtendNum());
                        aggregatedVo.setPegTotal(vo.getTotalNum());
                    }else if ("氟化锂".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setFhlSupplier(vo.getSupplierNum());
                        aggregatedVo.setFhlActual(vo.getActualNum());
                        aggregatedVo.setFhlRefill(vo.getExtendNum());
                        aggregatedVo.setFhlTotal(vo.getTotalNum());
                    }else if ("葡萄糖".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setGsSupplier(vo.getSupplierNum());
                        aggregatedVo.setGsActual(vo.getActualNum());
                        aggregatedVo.setGsRefill(vo.getExtendNum());
                        aggregatedVo.setGsTotal(vo.getTotalNum());
                    }
                }
            }
            newProductPeiJizhongVos.add(aggregatedVo);
        }
        results.put("list", newProductPeiJizhongVos);
        String fileName = CommonUtil.generateRandomNum("db-") + ".xlsx";
        String filePath = config.filePath + fileName;
//        String formattedStartTime = queryForm.getStartTime().substring(0, 10);
//        String formattedEndTime = queryForm.getEndTime().substring(0, 10);
        String nameStr = "投料批次明细"+ ".xlsx";
        TemplateExcelUtils.downLoadExcel(filePath, nameStr, results, "tlpc.xlsx", response);
    }

    @Override
    public void exportJizhongListByDay(QueryForm queryForm, HttpServletResponse response) throws Exception {
        Map<String, Object> results = Maps.newHashMap();

        if (StringUtils.isEmpty(queryForm.getStartTime())) {
            // 判断当前时间属于白班还是夜班
            // 获取当前时间
//            LocalDateTime now = LocalDateTime.now();
//            setShiftTimes(queryForm, now);
            Map<String,String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
            queryForm.setBanCi(dutyMap.get("whiteDay"));
            queryForm.setDutyDay(dutyMap.get("dutyDay"));
        }

        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectPcByTou(queryForm);
        Map<String, ProductPeiJizhongVo> factoryAggregatedMap = new HashMap<>();

        for (ProductPeiTou peiTou : productPeiTous) {
            ProductPeiJizhongExample jizhongExample = new ProductPeiJizhongExample();
            jizhongExample.createCriteria().andPeiIdEqualTo(peiTou.getId()).andStatusEqualTo(Constants.NORMAL_STATUS);
            List<ProductPeiJizhong> productPeiJizhongs = productPeiJizhongMapper.selectByExample(jizhongExample);

            for (ProductPeiJizhong vo : productPeiJizhongs) {
                String factoryName = peiTou.getFactoryName();
                ProductPeiJizhongVo aggregatedVo = factoryAggregatedMap.computeIfAbsent(factoryName, k -> new ProductPeiJizhongVo());
                Set<String> peiIds = aggregatedVo.getPeiIds();
                if (peiIds == null) {
                    peiIds = new HashSet<>();
                    aggregatedVo.setPeiIds(peiIds);
                }
                peiIds.add(peiTou.getId());
                aggregatedVo.setCount(productPeiTous.size());
                aggregatedVo.setFactoryName(factoryName);
                aggregatedVo.setQiStartTime(peiTou.getQiStartTime());
                aggregatedVo.setGradeValueName(peiTou.getProductName() + peiTou.getGradeValue());

                // 累加每种材料的总量
                if ("原料".equals(vo.getMaterialType())||"主料".equals(vo.getMaterialType())) {
                    if ("去离子水".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setWaterTotal(String.format("%.3f", getTotal(aggregatedVo.getWaterTotal(), vo.getTotalNum())));
                    } else if ("磷酸铁".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setFeTotal(String.format("%.3f", getTotal(aggregatedVo.getFeTotal(), vo.getTotalNum())));
                    } else if ("碳酸锂".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setLiTotal(String.format("%.3f", getTotal(aggregatedVo.getLiTotal(), vo.getTotalNum())));
                    }
                } else if ("辅料".equals(vo.getMaterialType())) {
                    if ("钛".equals(vo.getMaterialGrade())) {
                        aggregatedVo.settTotal(String.format("%.3f", getTotal(aggregatedVo.gettTotal(), vo.getTotalNum())));
                    } else if ("聚乙二醇".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setPegTotal(String.format("%.3f", getTotal(aggregatedVo.getPegTotal(), vo.getTotalNum())));
                    } else if ("氟化锂".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setFhlTotal(String.format("%.3f", getTotal(aggregatedVo.getFhlTotal(), vo.getTotalNum())));
                    } else if ("葡萄糖".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setGsTotal(String.format("%.3f", getTotal(aggregatedVo.getGsTotal(), vo.getTotalNum())));
                    }
                }

            }
        }
        for (ProductPeiJizhongVo aggregatedVo : factoryAggregatedMap.values()) {
            aggregatedVo.setCount(aggregatedVo.getPeiIds().size());
        }
        results.put("list", factoryAggregatedMap.values());
        String fileName = CommonUtil.generateRandomNum("db-") + ".xlsx";
        String filePath = config.filePath + fileName;
        String formattedStartTime = queryForm.getStartTime().substring(0, 10);
        String formattedEndTime = queryForm.getEndTime().substring(0, 10);
        String nameStr = "投料单日统计"+formattedStartTime+"-"+ formattedEndTime+".xlsx";
        TemplateExcelUtils.downLoadExcel(filePath, nameStr, results, "tldr.xlsx", response);
    }





    private void setShiftTimes(QueryForm queryForm, LocalDateTime now) {
        LocalTime time = now.toLocalTime();
        if (time.isAfter(LocalTime.of(8, 0)) && time.isBefore(LocalTime.of(20, 0))) {
            // A班：早上8点到晚上8点
            LocalDateTime startTime = LocalDateTime.of(now.toLocalDate(), LocalTime.of(8, 0));
            LocalDateTime endTime = LocalDateTime.of(now.toLocalDate(), LocalTime.of(19, 59, 59));
            queryForm.setStartTime(startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            queryForm.setEndTime(endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        } else {
            // B班：晚上8点到早上8点
            LocalDateTime startTime = LocalDateTime.of(now.toLocalDate().minusDays(1), LocalTime.of(20, 0));
            LocalDateTime endTime = LocalDateTime.of(now.toLocalDate(), LocalTime.of(7, 59, 59));
            queryForm.setStartTime(startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            queryForm.setEndTime(endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
    }

    @Override
    public List<ProductPeiJizhong> getProductPeiJizhongListByPeiId(String peiId) throws Exception {
        ProductPeiJizhongExample example = new ProductPeiJizhongExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andPeiIdEqualTo(peiId);
        List<ProductPeiJizhong> jizhongs = productPeiJizhongMapper.selectByExample(example);
        if(CollectionsUtil.isEmpty(jizhongs)){
            Map<String,String> itemMap = sysItemService.getMgItemNameMap(new QueryForm());
            ProductPeiJobSupplierExample supplierExample = new ProductPeiJobSupplierExample();
            supplierExample.createCriteria().andPeiIdEqualTo(peiId).andStatusEqualTo(Constants.NORMAL_STATUS);
            List<ProductPeiJobSupplier> suppliers = productPeiJobSupplierMapper.selectByExample(supplierExample);
            Map<String,ProductPeiJizhong> jzMap = Maps.newHashMap();
            if(CollectionsUtil.isNotEmpty(suppliers)){
                for(ProductPeiJobSupplier supplier :suppliers){
                    String materialId = supplier.getMaterialId();
                    String materialType = itemMap.get(materialId);
                    String materialGrade = supplier.getMaterialType();
                    String key  = materialType+"-"+materialGrade;
                    if(jzMap.containsKey(key)){
                        ProductPeiJizhong exist = jzMap.get(key);
                        String content = supplier.getMaterialName()+supplier.getSupplierCode()+"-"+supplier.getPeiNum();
                        exist.setSupplierNum(exist.getSupplierNum()+"，"+content);
                        continue;
                    }
                    ProductPeiJizhong jizhong = new ProductPeiJizhong();
                    jizhong.setPeiId(peiId);
                    jizhong.setMaterialType(materialType);
                    jizhong.setMaterialGrade(supplier.getMaterialType());
                    String content =  supplier.getMaterialName()+supplier.getSupplierCode()+"-"+supplier.getPeiNum();
                    jizhong.setSupplierNum(content);
                    jizhong.setActualNum("0");
                    jizhong.setExtendNum("0");
                    jizhong.setTotalNum("0");
                    jzMap.put(key,jizhong);
                }
                for(String key:jzMap.keySet()){
                    jizhongs.add(jzMap.get(key));
                }
                ProductPeiJizhong fixJizhong = new ProductPeiJizhong();
                fixJizhong.setPeiId(peiId);
                fixJizhong.setMaterialType("原料");
                fixJizhong.setMaterialGrade("去离子水");
                fixJizhong.setSupplierNum("/");
                fixJizhong.setActualNum("0");
                fixJizhong.setExtendNum("0");
                jizhongs.add(fixJizhong);
            }
        }
        Collections.sort(jizhongs, new Comparator<ProductPeiJizhong>() {
            @Override
            public int compare(ProductPeiJizhong o1, ProductPeiJizhong o2) {
                String o1Grade = o1.getMaterialGrade();
                String o2Grade = o2.getMaterialGrade();
                if(StringUtils.equals(o1Grade,"去离子水")){
                    return 1;
                }
                if(StringUtils.equals(o2Grade,"去离子水")){
                    return 1;
                }
                String o1Name = o1.getMaterialType();
                String o2Name = o2.getMaterialType();
                String key1 = o1Name+o1Grade;
                String key2 = o2Name+o2Grade;
                return key1.compareTo(key2);
            }
        });

        return jizhongs;
    }

    @Override
    public String addBatchInsertProductPeiJizhongs(List<ProductPeiJizhong> productPeiJizhongs) throws Exception {
        if(CollectionsUtil.isEmpty(productPeiJizhongs)){
            return "数组为空";
        }
        String peiId = productPeiJizhongs.get(0).getPeiId();
        ProductPeiJizhongExample example = new ProductPeiJizhongExample();
        example.createCriteria().andPeiIdEqualTo(peiId);
        int count =  productPeiJizhongMapper.deleteByExample(example);
        if(count < 0){
            return "删除异常！";
        }
        Map<String,String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        for(ProductPeiJizhong jz:productPeiJizhongs){
            jz.setId(CommonUtil.generateRandomNum("jz-"));
            jz.setDutyDay(dutyMap.get("dutyDay"));
        }
        count = productPeiJizhongMapper.batchInsertPeiJiZhongs(productPeiJizhongs);
        if(count < 1){
            throw new Exception("插入计重表异常！");
        }
        String jzStatus = productPeiJizhongs.get(0).getJzStatus();
        String jzUserName = productPeiJizhongs.get(0).getJzUserName();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String jzTime = simpleDateFormat.format(new Date());
        ProductPeiTou productPeiTou = new ProductPeiTou();
        productPeiTou.setJiWeightStatus(jzStatus);
        productPeiTou.setId(peiId);
        productPeiTou.setJiWeightTime(jzTime);
        productPeiTou.setJiWeightUser(jzUserName);
        ProductPeiTouExample productPeiTouExample = new ProductPeiTouExample();
        productPeiTouExample.createCriteria().andIdEqualTo(peiId);
        count = productPeiTouMapper.updateByExampleSelective(productPeiTou,productPeiTouExample);
        if(count < 1){
            throw new Exception("更新配投的计重状态异常！");
        }
        String collectId = productPeiJizhongs.get(0).getCollectId();
        if(StringUtils.isNotEmpty(collectId)){
            String resp = productPeiJizhongCollectService.updateProductPeiJizhongCollectById(collectId);
            if(StringUtils.isNotEmpty(resp)){
                throw new Exception(resp);
            }
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public Map<String, Object> getByIds(QueryForm queryForm) throws Exception {
        List<String> ids = queryForm.getIds();

        // pei_id 分组
        Map<String, ProductPeiJizhongVo> peiIdAggregatedMap = new HashMap<>();
        //按班次（A班、B班等）合计
        Map<String, ProductPeiJizhongVo> banCiAggregatedMap = new HashMap<>();
        // 合计数据
        ProductPeiJizhongVo totalAggregatedVo = new ProductPeiJizhongVo();

        // 查询ProductPeiTou数据
        ProductPeiTouExample example = new ProductPeiTouExample();
        example.createCriteria().andIdIn(ids);
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectByExample(example);

        // 遍历ProductPeiTou数据
        for (ProductPeiTou peiTou : productPeiTous) {
            ProductPeiJizhongExample jizhongExample = new ProductPeiJizhongExample();
            jizhongExample.createCriteria().andPeiIdEqualTo(peiTou.getId()).andStatusEqualTo(Constants.NORMAL_STATUS);
            List<ProductPeiJizhong> productPeiJizhongs = productPeiJizhongMapper.selectByExample(jizhongExample);

            // 遍历每个peiTou下的ProductPeiJizhong数据
            for (ProductPeiJizhong vo : productPeiJizhongs) {
                String peiId = vo.getPeiId();
                String banCi = peiTou.getWhiteDuty();  // A班或B班

                ProductPeiJizhongVo aggregatedVo = peiIdAggregatedMap.computeIfAbsent(peiId, k -> new ProductPeiJizhongVo());
                aggregatedVo.setQiStartTime(peiTou.getQiStartTime());
                aggregatedVo.setBanCi(StringUtils.equals(banCi, "1") ? "A" : "B");
                aggregatedVo.setStartCode(peiTou.getStartCode());
                aggregatedVo.setGradeValueName(peiTou.getProductName() + peiTou.getGradeValue());

                // 累加每种材料的总量（原料和辅料）
                if ("原料".equals(vo.getMaterialType())||"主料".equals(vo.getMaterialType())) {
                    if ("去离子水".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setWaterTotal(String.format("%.3f", getTotal(aggregatedVo.getWaterTotal(), vo.getTotalNum())));
                    } else if ("磷酸铁".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setFeTotal(String.format("%.3f", getTotal(aggregatedVo.getFeTotal(), vo.getTotalNum())));
                    } else if ("碳酸锂".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setLiTotal(String.format("%.3f", getTotal(aggregatedVo.getLiTotal(), vo.getTotalNum())));
                    }
                } else if ("辅料".equals(vo.getMaterialType())) {
                    if ("钛".equals(vo.getMaterialGrade())) {
                        aggregatedVo.settTotal(String.format("%.3f", getTotal(aggregatedVo.gettTotal(), vo.getTotalNum())));
                    } else if ("聚乙二醇".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setPegTotal(String.format("%.3f", getTotal(aggregatedVo.getPegTotal(), vo.getTotalNum())));
                    } else if ("氟化锂".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setFhlTotal(String.format("%.3f", getTotal(aggregatedVo.getFhlTotal(), vo.getTotalNum())));
                    } else if ("葡萄糖".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setGsTotal(String.format("%.3f", getTotal(aggregatedVo.getGsTotal(), vo.getTotalNum())));
                    }
                }

                for (ProductPeiJizhongVo banCiAggregatedVo : banCiAggregatedMap.values()) {
                    totalAggregatedVo.setWaterTotal(String.format("%.3f", getTotal1(totalAggregatedVo.getWaterTotal(), banCiAggregatedVo.getWaterTotal())));
                    totalAggregatedVo.setFeTotal(String.format("%.3f", getTotal1(totalAggregatedVo.getFeTotal(), banCiAggregatedVo.getFeTotal())));
                    totalAggregatedVo.setFhlTotal(String.format("%.3f", getTotal1(totalAggregatedVo.getFhlTotal(), banCiAggregatedVo.getFhlTotal())));
                    totalAggregatedVo.setGsTotal(String.format("%.3f", getTotal1(totalAggregatedVo.getGsTotal(), banCiAggregatedVo.getGsTotal())));
                    totalAggregatedVo.setLiTotal(String.format("%.3f", getTotal1(totalAggregatedVo.getLiTotal(), banCiAggregatedVo.getLiTotal())));
                    totalAggregatedVo.setPegTotal(String.format("%.3f", getTotal1(totalAggregatedVo.getPegTotal(), banCiAggregatedVo.getPegTotal())));
                    totalAggregatedVo.settTotal(String.format("%.3f", getTotal1(totalAggregatedVo.gettTotal(), banCiAggregatedVo.gettTotal())));
                }
                // 按班次聚合数据
                ProductPeiJizhongVo banCiAggregatedVo = banCiAggregatedMap.computeIfAbsent(banCi, k -> new ProductPeiJizhongVo());
                banCiAggregatedVo.setQiStartTime(peiTou.getQiStartTime());
                banCiAggregatedVo.setBanCi(banCi);
                banCiAggregatedVo.setGradeValueName(peiTou.getProductName() + peiTou.getGradeValue());

                // 累加每种材料的总量（根据班次）
                if ("原料".equals(vo.getMaterialType())||"主料".equals(vo.getMaterialType())) {
                    if ("去离子水".equals(vo.getMaterialGrade())) {
                        banCiAggregatedVo.setWaterTotal(String.format("%.3f", getTotal(banCiAggregatedVo.getWaterTotal(), vo.getTotalNum())));
                    } else if ("磷酸铁".equals(vo.getMaterialGrade())) {
                        banCiAggregatedVo.setFeTotal(String.format("%.3f", getTotal(banCiAggregatedVo.getFeTotal(), vo.getTotalNum())));
                    } else if ("碳酸锂".equals(vo.getMaterialGrade())) {
                        banCiAggregatedVo.setLiTotal(String.format("%.3f", getTotal(banCiAggregatedVo.getLiTotal(), vo.getTotalNum())));
                    }
                } else if ("辅料".equals(vo.getMaterialType())) {
                    if ("钛".equals(vo.getMaterialGrade())) {
                        banCiAggregatedVo.settTotal(String.format("%.3f", getTotal(banCiAggregatedVo.gettTotal(), vo.getTotalNum())));
                    } else if ("聚乙二醇".equals(vo.getMaterialGrade())) {
                        banCiAggregatedVo.setPegTotal(String.format("%.3f", getTotal(banCiAggregatedVo.getPegTotal(), vo.getTotalNum())));
                    } else if ("氟化锂".equals(vo.getMaterialGrade())) {
                        banCiAggregatedVo.setFhlTotal(String.format("%.3f", getTotal(banCiAggregatedVo.getFhlTotal(), vo.getTotalNum())));
                    } else if ("葡萄糖".equals(vo.getMaterialGrade())) {
                        banCiAggregatedVo.setGsTotal(String.format("%.3f", getTotal(banCiAggregatedVo.getGsTotal(), vo.getTotalNum())));
                    }
                }

            }
        }

        Map<String, Object> result = new HashMap<>();

        totalAggregatedVo.setCount(peiIdAggregatedMap.size());

        result.put("totalAggregatedData", totalAggregatedVo);
        result.put("peiIdAggregatedData", peiIdAggregatedMap);
        result.put("banCiAggregatedData", banCiAggregatedMap);

        return result;
    }

    @Override
    public Map<String, Object> getJizhongListByHome(QueryForm queryForm) throws Exception {
        // 如果没有传时间
        if (StringUtils.isEmpty(queryForm.getStartTime())) {
            Map<String,String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
            queryForm.setBanCi(dutyMap.get("whiteDay"));
            queryForm.setDutyDay(dutyMap.get("dutyDay"));
        }
        List<ProductPeiTou> productPeiTous = productPeiTouMapper.selectPcByTou(queryForm);
        Map<String, ProductPeiJizhongVo> factoryAggregatedMap = new HashMap<>();
        Map<String, Object> result = new HashMap<>();
        List<ProductPeiJizhongVo> jizhongList = new ArrayList<>();
        for (ProductPeiTou peiTou : productPeiTous) {
            ProductPeiJizhongExample jizhongExample = new ProductPeiJizhongExample();
            jizhongExample.createCriteria().andPeiIdEqualTo(peiTou.getId()).andStatusEqualTo(Constants.NORMAL_STATUS);
            List<ProductPeiJizhong> productPeiJizhongs = productPeiJizhongMapper.selectByExample(jizhongExample);

            for (ProductPeiJizhong vo : productPeiJizhongs) {
                String factoryName = peiTou.getFactoryName();
                ProductPeiJizhongVo aggregatedVo = factoryAggregatedMap.computeIfAbsent(factoryName, k -> new ProductPeiJizhongVo());
                Set<String> peiIds = aggregatedVo.getPeiIds();
                if (peiIds == null) {
                    peiIds = new HashSet<>();
                    aggregatedVo.setPeiIds(peiIds);
                }
                peiIds.add(peiTou.getId());
                aggregatedVo.setCount(productPeiTous.size());
                aggregatedVo.setFactoryName(factoryName);
                aggregatedVo.setQiStartTime(peiTou.getQiStartTime());
                aggregatedVo.setGradeValueName(peiTou.getProductName() + peiTou.getGradeValue());

                // 累加每种材料的总量
                if ("原料".equals(vo.getMaterialType())||"主料".equals(vo.getMaterialType())) {
                    if ("去离子水".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setWaterTotal(String.format("%.3f", getTotal(aggregatedVo.getWaterTotal(), vo.getTotalNum())));
                    } else if ("磷酸铁".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setFeTotal(String.format("%.3f", getTotal(aggregatedVo.getFeTotal(), vo.getTotalNum())));
                    } else if ("碳酸锂".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setLiTotal(String.format("%.3f", getTotal(aggregatedVo.getLiTotal(), vo.getTotalNum())));
                    }
                } else if ("辅料".equals(vo.getMaterialType())) {
                    if ("钛".equals(vo.getMaterialGrade())) {
                        aggregatedVo.settTotal(String.format("%.3f", getTotal(aggregatedVo.gettTotal(), vo.getTotalNum())));
                    } else if ("聚乙二醇".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setPegTotal(String.format("%.3f", getTotal(aggregatedVo.getPegTotal(), vo.getTotalNum())));
                    } else if ("氟化锂".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setFhlTotal(String.format("%.3f", getTotal(aggregatedVo.getFhlTotal(), vo.getTotalNum())));
                    } else if ("葡萄糖".equals(vo.getMaterialGrade())) {
                        aggregatedVo.setGsTotal(String.format("%.3f", getTotal(aggregatedVo.getGsTotal(), vo.getTotalNum())));
                    }
                }

            }
        }
        for (ProductPeiJizhongVo aggregatedVo : factoryAggregatedMap.values()) {
            jizhongList.add(aggregatedVo);
        }
        // 计算合计数据
        ProductPeiJizhongVo totalVo = new ProductPeiJizhongVo();
        totalVo.setFactoryName("合计");
        Double totalWaterTotal = 0.0;
        Double totalLiTotal = 0.0;
        Double totalFeTotal = 0.0;
        Double totaltTotal = 0.0;
        Double totalPegTotal = 0.0;
        Double totalFhlTotal = 0.0;
        Double totalGsTotal = 0.0;
        for (ProductPeiJizhongVo vo : jizhongList) {
            totalWaterTotal += safeParseDouble(vo.getWaterTotal(), 0.0);
            totalLiTotal += safeParseDouble(vo.getLiTotal(), 0.0);
            totalFeTotal += safeParseDouble(vo.getFeTotal(), 0.0);
            totaltTotal += safeParseDouble(vo.gettTotal(), 0.0);
            totalPegTotal += safeParseDouble(vo.getPegTotal(), 0.0);
            totalFhlTotal += safeParseDouble(vo.getFhlTotal(), 0.0);
            totalGsTotal += safeParseDouble(vo.getGsTotal(), 0.0);
        }
        totalVo.setWaterTotal(String.format("%.3f", totalWaterTotal));
        totalVo.setLiTotal(String.format("%.3f", totalLiTotal));
        totalVo.setFeTotal(String.format("%.3f", totalFeTotal));
        totalVo.settTotal(String.format("%.3f", totaltTotal));
        totalVo.setPegTotal(String.format("%.3f", totalPegTotal));
        totalVo.setFhlTotal(String.format("%.3f", totalFhlTotal));
        totalVo.setGsTotal(String.format("%.3f", totalGsTotal));
        jizhongList.add(totalVo);
        result.put("result", jizhongList);
        return result;
    }
    private Double safeParseDouble(String value, Double defaultValue) {
        return value != null && !value.isEmpty() ? Double.parseDouble(value) : defaultValue;
    }


    //计算总量
    private double getTotal(String currentTotal, String newTotal) {
        // 转换为吨
        if (StringUtils.isEmpty(currentTotal)) {
            return Double.parseDouble(newTotal) / 1000.0;
        }
        return Double.parseDouble(currentTotal) + (Double.parseDouble(newTotal) / 1000.0);
    }

    private double getTotal1(String currentTotal, String newTotal) {
        try {
            if (StringUtils.isEmpty(currentTotal)) {
                return Double.parseDouble(newTotal);
            }
            return Double.parseDouble(currentTotal) + Double.parseDouble(newTotal);
        } catch (NumberFormatException e) {
            return Double.parseDouble(currentTotal);
        }
    }

}